package io.renren.modules.generator.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.renren.common.utils.*;
import io.renren.common.utils.excel.ExcelUtils;
import io.renren.modules.generator.dao.SequenceDao;
import io.renren.modules.generator.entity.OrderDetailEntity;
import io.renren.modules.generator.entity.OrdersEntity;
import io.renren.modules.generator.export.OrderExcelDataCreaterImpl;
import io.renren.modules.generator.export.TmsOrderImportDataCreaterImpl;
import io.renren.modules.generator.service.OrderDetailService;
import io.renren.modules.generator.service.OrdersService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-16 11:05:22
 */
@RestController
@RequestMapping("generator/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private SequenceDao sequenceDao;

    @Autowired
    private RedisService redisService;

    @Autowired
    private OrderExcelDataCreaterImpl orderExcelDataCreater;

    @Autowired
    private TmsOrderImportDataCreaterImpl tmsOrderImportDataCreater;


    @Autowired
    private ExcelUtils excelUtils;


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        Query query = new Query(params);

        List<OrdersEntity> list = ordersService.queryPage(query);

        int total =ordersService.queryPageTotal(params);

        PageUtils pageUtils = new PageUtils(list, total, query.getLimit(), query.getCurrPage());

        return R.ok().put("page", pageUtils);
    }


    /**
     * 修改只修改订单下面的某一条明细
     */
    @RequestMapping("/info")
    public R info(@RequestParam("orderDetailId") String orderDetailId,@RequestParam("orderId") String orderId){
			OrdersEntity orders = ordersService.queryByOrderDetailIdAndOrderId(orderId,orderDetailId);

        return R.ok().put("data", orders);
    }

    /**
     * 保存
     */
    @RequestMapping("/save/{flag}")
    @RequiresPermissions("generator:orders:save")
    public R save(@RequestBody OrdersEntity orders, @PathVariable String flag){
        ordersService.save(orders);
        if(flag.equals("0")){
            sequenceDao.getNextValue("order_sequence");
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("generator:orders:update")
    public R update(@RequestBody OrdersEntity orders){
        ordersService.update(orders);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:orders:delete")
    public R delete(@RequestBody Integer[] ids){
			ordersService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }




    @GetMapping("export")
    @RequiresPermissions("generator:orders:export")
    public void exportDate(@RequestParam Map<String, Object> params, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {

        String[] lableNames = {"状态","提货日期","到货日期","订单号","订单组号","提货地址代码","到货地址代码","产品代码","产品名称","数量","体积","重量","板数","创建人","创建时间",
                "提货省","提货市","提货区","提货详细地址","提货联系人","手机","电话","邮箱","到货省","到货市","到货区","到货详细地址","到货联系人","手机","电话","邮箱","温度","温区","单价","货值","实际发货数量","实际收货数量","数量差异","订单备注","更新时间","更新人","运单号","业务类型","运输类型","需要预约","客户自提","客户自送","需要卸货","预留字段1","预留字段2"};
        String[] columnNames={"status","fromDate","toDate","orderNumber","orderGroupNumber","fromAddressCode","toAddressCode","productNumber","productCnName",
                "quantity","orderDetailVolume","orderDetailWeight","orderDetailPlatesNumber","createdBy","createdTime","fromProvince","fromCity","fromArea",
                "fromDetailedAddress","fromLinkMan","fromLinkManPhone","fromLinkManTelement","fromLinkManEmail","toProvince","toCity","toArea","toDetailedAddress","toLinkMan","toLinkManPhone","toLinkManTelement","toLinkManEmail","productTemperatureRange","productTemperatureRangeCode","price","productValue","actualSendQuantity"
                ,"actualReceiveQuantity","quantityDifference","remark","orderDetailLastModifiedTime","orderDetailLastModifiedBy","transportationOrderNo","businessType","transportationType","appointFlag","slfPickupFlag","slfDeliverFlag","unloadFlag","extendFirst","extendSecond"};
        excelUtils.export(response,"数据导出.xlsx",lableNames,columnNames,params,orderExcelDataCreater);

    }

    @GetMapping("importTms")
    public void importTmsDate(@RequestParam Map<String, Object> params, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {

        String[] lableNames = {"客户代码","业务类型","运输类型","订单组号","运单号","订单号","下单时间","车辆类型","温区1","温区2",
                "需要预约","客户自提","客户自送", "需求卸货","备注","要求发货时间","要求到货日期时间", "发货点代码","发货省","发货市",
                "发货区","发货详细地址","发货联系人","电话","收货点代码","收货省","收货市","收货区","收货详细地址","收货联系人","电话",
                "货品代码","货品名称","运输单位","数量","温区","毛重（千克）","体积（立方）"};
        String[] columnNames={"customerCode","businessType","transportationType","orderGroupNumber","transportationOrderNo","orderNumber",
                "createdTime","vehicleCode","productTemperatureRangeCode","productTemperatureRangeCode1","appointFlag","slfPickupFlag","slfDeliverFlag",
                "unloadFlag", "orderGroupRemark","fromDate","toDate","fromAddressCode","fromProvince","fromCity","fromArea",
                "fromDetailedAddress","fromLinkMan","fromLinkManTelement", "toAddressCode","toProvince","toCity","toArea",
                "toDetailedAddress","toLinkMan","toLinkManTelement", "productNumber","productCnName",
                "defaultMeasurementUnitName", "quantity","productTemperatureRangeType","productGrossWeight","productVolume"};
        excelUtils.export(response,"数据导出.xlsx",lableNames,columnNames,params,tmsOrderImportDataCreater);

    }



    @PostMapping("import")
    @RequiresPermissions("generator:orders:import")
    public R importPdf(@RequestParam("files") MultipartFile[] multipartFiles){
        if(multipartFiles.length > 0){
            for (MultipartFile file :
                    multipartFiles) {

                String filename = file.getOriginalFilename();

                int lastIndexOf = filename.lastIndexOf(".");

                String substring = filename.substring(lastIndexOf + 1, filename.length());
                if(!substring.equals("pdf")){
                    return R.error("文件类型错误，请上传pdf文件");
                }
            }
        }
        try {
            R r = ordersService.importPdfData(multipartFiles);
            for (MultipartFile file :
                    multipartFiles) {
                saveFile(file);
            }
            return r;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error();
    }

    private String saveFile(MultipartFile file) {
        try {
            if(file != null && !file.isEmpty()) {

                String filePath =ConfigConstant.FILE_PATH+file.getOriginalFilename();
                File fp = new File(new File(filePath).getParent());
                if(!fp.exists()){
                    fp.mkdirs();
                }
                DataOutputStream out = new DataOutputStream(new FileOutputStream(filePath));
                InputStream is = null;
                try {
                    is = file.getInputStream();
                    byte[] b=new byte[is.available()];
                    is.read(b);
                    out.write(b);
                    return filePath ;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }


    @GetMapping("/pdfFileToStream")
    public void pdfFileToStream(HttpServletResponse response,@RequestParam String fileName){
        File file = new File(ConfigConstant.FILE_PATH+fileName);
        FileInputStream fileInputStream = null;
        OutputStream outputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
            response.setContentType("application/octet-stream");
            outputStream = response.getOutputStream();

           IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 查询订单上所有的提货地和到货地
     */

    @GetMapping("/queryAllFromAddressAndAllToAddress")
    public R queryAllFromAddressAndAllToAddress(){
        return R.ok().put("data",ordersService.queryAllFromAddressAndAllToAddress());
    }


    /**
     * 更新订单状态
     */
    @GetMapping("/updateOrderStatusById")
    public R updateOrderStatusById(@RequestParam String status,@RequestParam Integer id){
        ordersService.updateOrderStatusById(status,id);
        return R.ok();
    }


    /**
     * 批量更新订单状态：已调度，取消调度
      */
    @PostMapping("/updateOrderStatusByIds")
    public R updateOrderStatusByIds(@RequestBody Map<String,Object> params){
        Object status = params.get("status");
        Object orderIds = params.get("orderIds");
        if(status != null){
            if(orderIds != null){
                String s= status.toString();
                List<Integer> ids = (List<Integer>) orderIds;
                ordersService.updateOrderStatusByIds(s,ids);
            }
        }


        return R.ok();
    }

    /**
     * 删除订单明细
     */
    @GetMapping("/deleteOrderDetailByDetailId")
    @RequiresPermissions("generator:orders:detail:delete")
    public R deleteOrderDetailByDetailId(@RequestParam Integer id, @RequestParam Integer orderDetailId){
        int selectCount = orderDetailService.selectCount(new EntityWrapper<OrderDetailEntity>()
                .eq(id != null, "order_id", id));
        orderDetailService.deleteById(orderDetailId);

        if(selectCount == 1){
            ordersService.deleteById(id);
            redisService.removePattern(RedisKeys.getOrderKey("*"));
        }

        return R.ok();
    }



    /**
     * 取消编组
     */
    @PostMapping("/cancelOrderGroupByIds")
    @RequiresPermissions("generator:ordersgroup:cancel")
    public R cancelOrderGroupByIds(@RequestBody List<JSONObject> params){

        Map<Integer,List<Integer>> map =new HashMap<>();

        for (JSONObject jsonObject: params
             ) {
            Integer orderGroupId = (Integer) jsonObject.get("orderGroupId");
            List<Integer> orderIds = (ArrayList<Integer>) jsonObject.get("orderIds");
            map.put(orderGroupId,orderIds);
        }

        ordersService.cancelOrderGroupByIds(map);
        return R.ok();
    }

    /**
     * 根据状态或订单组查询订单
     */
    @GetMapping("/queryByStatusAndGroupNumber")
    public R queryByStatusAndGroupNumber(@RequestParam String status,@RequestParam String orderGroupNumber ,@RequestParam Set<String> toAddressIds){
        List<OrdersEntity> ordersEntities = ordersService.queryOrder(status,orderGroupNumber,toAddressIds);
        return R.ok().put("data",ordersEntities);
    }

    /**
     * 根据订单组ID查询订单
     */
    @GetMapping("/queryOrdersByOrderGroupId")
    public R queryOrdersByOrderGroupId(@RequestParam int orderGroupId){
        List<OrdersEntity> ordersEntities =ordersService.queryOrdersByOrderGroupId(orderGroupId);
        return R.ok().put("data",ordersEntities);
    }

    /**
     * 将订单加入到已有的编组中
     */
    @GetMapping("/addOrderToOrderGroup")
    public R addOrderToOrderGroup(@RequestParam Set<Integer> orderIds,@RequestParam int orderGroupId ){
        ordersService.addOrderToOrderGroup(orderIds,orderGroupId);
        return R.ok();
    }



}
